import React, {Component} from 'react';
import {connect} from 'react-redux';
import {message} from 'antd';
import {messages} from "share/common";
import FileUpload from './file-upload';

class IndirectUpload extends Component {

  constructor(props) {
    super(props)
    this.file = {};
    this.sourceResult = {};
    this.finish = false;
    this.state = {
      fileList: [],
      uploading: false,
    }
  }

  componentWillReceiveProps(nextProps) {
    const {isUpload, finishUpload} = nextProps;
    const {fileList} = this.state;
    if (isUpload === true) {
      if (fileList.length > 0) {
        if (this.finish) {
          finishUpload(this.sourceResult);
        } else {
          message.error(messages('financial-management.key927')/*正在解析文件，请稍候*/);
        }
      } else {
        message.error(messages('financial-management.key736')/*请先上传文件*/);
        finishUpload({});
      }
    }
  }

  beforeUpload = (file) => {
    const {returnFileList} = this.props;
    this.file = file;
    if (returnFileList) {
      returnFileList([this.file]);
    }
    this.setState({fileList: [JSON.parse(JSON.stringify(this.file))]});
    return true;
  }

  uploadSuccess = (res) => {
    this.sourceResult = res;
    this.finish = true;
    this.setState({
      uploading: false,
      testData: {data: res},
    });
    const {finishUpload, isUpload} = this.props;
    (isUpload === undefined) && finishUpload(this.sourceResult || {});
  }

  fileUploadOption = () => {
    const {uploadUrl, params, authToken} = this.props;
    return {
      data: params,
      beforeUpload: this.beforeUpload,
      uploadUrl: uploadUrl,
      token: (uploadUrl.indexOf('vendor-data-service') > -1) ? localStorage.getItem('public.token') : authToken.access_token,
      onChange: this.uploadSuccess,
    };
  }

  render() {
    const {fileList} = this.state;
    const {style} = this.props;
    return (
      <div style={style}>
        {
          !window.ISIE9 && fileList.map(item => {
            return (<p style={{margin: 0}}>{item.name}</p>)
          })
        }
        <FileUpload {...this.fileUploadOption()}/>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    authToken: state.main.authToken
  }
}

export default connect(mapStateToProps)(IndirectUpload);

/***
 * isUpload         boolean      是否开始上传
 * uploadUrl        String       上传地址
 * finishUpload     function     上传完成回调
 * returnFileList   function     返回所选文件
 * params           object       参数
 * style
 */

